package com.wan.fragment


import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.RelativeLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions

import com.wan.R
import com.wan.activity.CommonlyUsedActivity
import com.wan.activity.SearchActivity
import com.wan.activity.WebActivity
import com.wan.adapter.HeaderAndFooterAdapter
import com.wan.adapter.HomeRvAdapter
import com.wan.adapter.HomeVpAdapter
import com.wan.base.BaseBean
import com.wan.entity.HomeArtEntity
import com.wan.entity.HomeArtItemEntity
import com.wan.entity.HomeBannerEntity
import com.wan.uitls.*
import com.wan.view.HomeIndication
import kotlinx.android.synthetic.main.fragment_home.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

/**
 * 首页碎片
 * 一个轮播图
 * 一个常用专区
 * 一个最新博文
 *
 */
class HomeFragment : Fragment(), ItemClickListener, PagerChangeListener, PagerItemClickListener, ItemRightViewListener {


    private lateinit var headerAdapter: HeaderAndFooterAdapter

    private var page: Int = 0

    //文章列表
    private var articleList = ArrayList<HomeArtItemEntity>()
    //轮播图 列表
    private var bannerList = ArrayList<HomeBannerEntity>()

    private lateinit var viewPager: ViewPager
    private lateinit var headView: View

    private lateinit var artListCall: Call<BaseBean<HomeArtEntity>>
    private lateinit var bannerListCall: Call<BaseBean<ArrayList<HomeBannerEntity>>>

    private val timeService = Executors.newScheduledThreadPool(1)


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initAdapter()

    }




    private fun initAdapter() {
        home_blog_rv.layoutManager = LinearLayoutManager(context)
        var homeAdapter = HomeRvAdapter(context!!, articleList, R.layout.fragment_home_item_layout)
        homeAdapter.setItemClickListener(this)
        homeAdapter.setRightViewListener(this)

        headView = LayoutInflater.from(context!!).inflate(R.layout.fragment_home_header_layout, home_blog_rv, false)
        headerAdapter = HeaderAndFooterAdapter(homeAdapter)
        headerAdapter.addHeaderView(headView)
        home_blog_rv.adapter = headerAdapter


        initHeadView(headView)
        initNetWork()

    }
    private fun initHeadView(headView: View?) {
        viewPager = headView!!.findViewById(R.id.home_banner_vp)

        var toolBtn = headView.findViewById<Button>(R.id.home_zone_tool_btn)
        var siteBtn = headView.findViewById<Button>(R.id.home_zone_site_btn)
        toolBtn.setOnClickListener {
            CommonUtils.toastWord(context!!, "跳转至工具")
            startActivity(Intent(context!!, SearchActivity::class.java))
        }

        siteBtn.setOnClickListener {
            CommonUtils.toastWord(context!!, "跳转至网站")
            startActivity(Intent(context!!, CommonlyUsedActivity::class.java))
        }
    }

    private fun initNetWork() {
        var api: ApiManager = ApiManager(this)
        api.getArticleList(page).enqueue(object : Callback<BaseBean<HomeArtEntity>> {
            override fun onFailure(call: Call<BaseBean<HomeArtEntity>>, t: Throwable) {
                println("failure ==> ${t.message}")
                CommonUtils.toastWord(context!!, "请求失败")
            }

            override fun onResponse(call: Call<BaseBean<HomeArtEntity>>, response: Response<BaseBean<HomeArtEntity>>) {
                var homeArtEntity = response.body()!!.data
                CommonUtils.toastWord(context!!, "请求成功")
                var arrayList = homeArtEntity.datas
                articleList.addAll(arrayList)

                headerAdapter.notifyDataSetChanged()
            }

        })



        api.getHomeBannerList().enqueue(object : Callback<BaseBean<ArrayList<HomeBannerEntity>>> {
            override fun onFailure(call: Call<BaseBean<ArrayList<HomeBannerEntity>>>, t: Throwable) {
                CommonUtils.toastWord(context!!, "请求banner 失败")
            }

            override fun onResponse(call: Call<BaseBean<ArrayList<HomeBannerEntity>>>, response: Response<BaseBean<ArrayList<HomeBannerEntity>>>) {
                CommonUtils.toastWord(context!!, "请求banner 成功")
                var data = response.body()!!.data
                bannerList.addAll(data)
                initViewPager()
            }
        })

    }

    override fun onItemClickListener(position: Int) {
        var homeBean = articleList[position]
        CommonUtils.toastWord(context!!, "$homeBean")
        CommonUtils.sendIntent(context!!, WebActivity::class.java, homeBean.link, homeBean.title)
    }

    override fun onRightViewClickListener(position: Int) {
        headerAdapter.notifyDataSetChanged()
    }




    //************轮播图*************//

    private val vpTag: Int = 0x001
    private var currentPage: Int = 0


    private val handler = Handler {
        when (it!!.what) {
            vpTag -> {
                if (currentPage >= bannerList.size) {
                    currentPage = 0
                } else {
                    currentPage++
                }
                viewPager.currentItem = currentPage
            }
        }

        true

    }


    private val timeRunnable: Runnable = Runnable {
        handler.sendEmptyMessage(vpTag)
    }


    private fun initViewPager() {
        var relativeLayout = headView!!.findViewById<RelativeLayout>(R.id.home_banner_indication)
        var views: ArrayList<View> = ArrayList()
        for (i in 0 until bannerList.size) {
            var rootView = LayoutInflater.from(context).inflate(R.layout.home_banner_item, viewPager, false)
            var imageView = rootView.findViewById<ImageView>(R.id.home_banner_item_iv)
            var options = RequestOptions()
                    .placeholder(R.mipmap.ic_launcher)
            Glide.with(context!!)
                    .load(bannerList[i].imagePath)
                    .apply(options)
                    .into(imageView)
            views.add(rootView)
        }
        viewPager.addOnPageChangeListener(HomeIndication(context!!, bannerList, relativeLayout, this))
        viewPager.offscreenPageLimit = bannerList.size - 1
        viewPager.adapter = HomeVpAdapter(views, this)
        timeService.scheduleAtFixedRate(timeRunnable, 3, 3, TimeUnit.SECONDS)
    }

    override fun onPagerItemClickListener(position: Int) {
        var bannerEntity = bannerList[position]
        CommonUtils.sendIntent(context!!, WebActivity::class.java, bannerEntity.url, bannerEntity.title)
    }

    override fun onPageChangeListener(position: Int) {
        currentPage = position
    }

    override fun onDestroy() {
        timeService.shutdown()
        handler.removeCallbacksAndMessages(null)
        RetrofitHelper.get().cancelCall(this)
        super.onDestroy()
    }

}


